$(document).ready(function(){
    
    /***  分类 begin   ***/
    var integralClass = '';
    function getIntegralClass(){
        getAjax(`${global.apiUrl}/get_jf_shop_class`,function(res){
            // console.log(res);
            var html = '';
            var addBusinessClass = '';
            var selHtml = '<option value="0">全部</option>';
            integralClass = res;
            for(var i in res){
                html += `
                    <div class="class-item">
                    <div class="icon-box">
                        <img src="../../img/community-service/shop.png" alt="">
                    </div>
                    <div class="icon-text">${res[i].class_name}</div>
                    <div class="class-reset themeColor" data-toggle="modal" data-target="#classModal" data-type="2" data-id="${res[i].id}">修改</div>
                    <div class="class-delete themeColor" data-id="${res[i].id}">删除</div>
                </div>
                `
                selHtml += `
                     <option value="${res[i].id}">${res[i].class_name}</option>
                     
                `
                addBusinessClass += `
                    <div class="checkbox">
                        <label>
                            <input type="radio" class="class-checked" name="class" value="${res[i].id}"> ${res[i].class_name}
                        </label>
                    </div>
                `
            }
            html += `
                <div class="class-item-add" data-toggle="modal" data-target="#classModal" data-type="1">
                    <div class="icon-box-add">
                        <img src="../../img/community-service/banner_add.png" alt="">
                    </div>
                    <div class="icon-text-add">添加</div>
                </div>
            `
            $('#integralClass').html(html);
            $('#integral-class-sel ').html(selHtml);
            $('#add-shop-class-box').html(addBusinessClass);

        },{
            community_id: global.community_id
        })
    }
    getIntegralClass();

    $('.class-box').on('mouseenter','.class-item',function(){
        // console.log(1);
        $(this).css('boxShadow','0 0 8px #f1f1f1');
        $(this).find('.class-reset').css('display','block');
        $(this).find('.class-delete').css('display','block');
    })
    $('.class-box').on('mouseleave','.class-item',function(){
        $(this).css('boxShadow','');
        $(this).find('.class-reset').css('display','none');
        $(this).find('.class-delete').css('display','none');
    })

    $('#classModal').on('show.bs.modal',function(event){
        var modal = $(this);
        var btnThis = $(event.relatedTarget);
        var type = btnThis.data('type');
        // console.log(type);
        modal.find('#className').val('');
        modal.find('.preview-class-img').html(`<div>图片预览</div>`);
        if(type == 1){
            modal.find('#classModalLabel').text('添加分类');
            modal.find('#uploadClassImg').attr('data-type','1');
            modal.find('#classItemId').val('');
        }else if(type == 2){
            modal.find('#classModalLabel').text('修改分类');
            modal.find('#uploadClassImg').attr('data-type','2');
            var id = btnThis.data('id');
            // console.log(id);
            // console.log(id,mainBanner);
            modal.find('#classItemId').val(id);
            for(var i in integralClass){
                if(id == integralClass[i].id){
                    modal.find('.preview-class-img').html(`<img src="${integralClass[i].url}" >`);
                    modal.find('#className').val(integralClass[i].class_name);
                }
            }
        }
    })
    //上传图片获取图片地址
    $('#uploadClassImg').on('click',function(){
        var $className = $('#className').val();
        var $classId = $('#classItemId').val();
        var type = $('#uploadClassImg').data('type');
        // console.log($classImgUrl,$classId,$className);
        // console.log(type);
        var data = {
            "id": $classId,
            "class_name": $className,
            "community_id": global.community_id
        }
        data = JSON.stringify(data)
        getAjax(`${global.apiUrl}/operation_community_jf_shop_class`,function(res){
            if(res == 1){
                getIntegralClass();
                alert('上传成功！');
                $('#classModal').modal('hide');
            }
        },{
            type:type,
            pro: data
        })
    })
    $('#integralClass').on('click','.class-delete',function(){
        var id = $(this).data('id');
        // console.log(id);
        var f = confirm('删除分类可能造成！软件异常，是否确实删除');
        if(f){
            getAjax(`${global.apiUrl}/operation_community_jf_shop_class`,function(res){
                // console.log(res);
                if(res == 1){
                   getHomemakingClass();
                //    console.log(res);
                   alert('删除成功！')
               }else if(res == 2){
                   alert('该分类存在商品！不可删除！');
               }

            },{
                type:3,
                id:id
            })
        }
    })
    /***  商户列表  ***/
    var timeFlag = true
    var priceFlag = true
    var type = 1
    var like = ''
    $('.sortItemAre').on('click',function(){
        var sortType = $(this).data('type')
        // console.log(timeFlag)
        // console.log(priceFlag)
        
        $('#timeImg').attr('src','../../img/community-service/up.png')
        $('#priceImg').attr('src','../../img/community-service/up.png')
        $('.timeTxt').css('color','black')
        $('.priceTxt').css('color','black')
        if(sortType == 'time'){
            $('.timeTxt').css('color','#0b67ff')
            if(timeFlag == true){
                timeFlag = false
                $('#timeImg').attr('src','../../img/community-service/downBlue.png')      
                type = 2          
                getGoodsList(goodsPageNo,showNum,type,like);
            }else{
                timeFlag = true
                $('#timeImg').attr('src','../../img/community-service/upBlue.png')   
                type = 1  
                getGoodsList(goodsPageNo,showNum,type,like);
            }
        }else if(sortType == 'price'){
            $('.priceTxt').css('color','#0b67ff')
            if(priceFlag == true){
                priceFlag = false
                $('#priceImg').attr('src','../../img/community-service/downBlue.png')      
                type = 4   
                getGoodsList(goodsPageNo,showNum,type,like);       
            }else{
                priceFlag = true
                $('#priceImg').attr('src','../../img/community-service/upBlue.png')   
                type = 3  
                getGoodsList(goodsPageNo,showNum,type,like);
            }
        }
    })

    $('#searchTxt').on('click',function(){
        like = $('.search-box').val()
        getGoodsList(goodsPageNo,showNum,type,like);
    })
    //获取商品列表
    var goodsPageNo = 1,showNum=10;
    var goodsList = '';
    function getGoodsList(p,showNum,type,like){
        getAjax(`${global.apiUrl}/user_get_community_jf_shop_product`,function(res){
            console.log(res);
            if(res.list.length == 0){
                $("#page").paging({
                    pageNo:0,
                    totalPage: 0, //总页数
                    totalSize: 0,
                    callback: function(num) {
                        getGoodsList(num,showNum,type,like)
                    }
                });
                var html = `
                        <tr>
                            <td colspan="7" align="center">暂无商品</td>
                        </tr>`
                $('#goodsList').html(html);
            }else{
                $("#page").paging({
                    pageNo:p,
                    totalPage: Math.ceil(res.count/showNum), //总页数
                    totalSize: res.count,
                    callback: function(num) {
                        getGoodsList(num,showNum,type,like)
                        goodsPageNo = num
                    }
                });
                var html = '';
                goodsList = res.list;
                var list = res.list;
                for(var i in list){
                    html += `
                        <tr>
                            <td class="shop-img">
                                <img src="${list[i].head_img}" alt="">
                            </td>
                            <td>${list[i].product_name}</td>
                            <td>${list[i].gg}</td>
                            <td>${list[i].jf}</td>
                            <td>${list[i].no_pay}</td>
                            <td>${list[i].yes_pay?list[i].yes_pay:0}</td>
                            <td class="control-td themeColor">
                                <span class="reset" data-toggle="modal" data-target="#GoodsModal" data-id="${list[i].id}" data-type="2">修改</span>
                                <span class="delete" data-id="${list[i].id}" style="margin-left: 15px">删除</span>
                            </td>
                        </tr>
                `
                }
                $('#goodsList').html(html);
            }
        },{
            p:p,
            num:showNum,
            type: type,
            product_name: like,
            community_id: global.community_id
        })
    }
    getGoodsList(goodsPageNo,showNum,type,like);


    /** 添加商品 **/
    function setShopImgUrl(res){
        document.getElementById('goods-img-url').value = res;
    }
    imgUpload('goods-img-select','goods-img-show',setShopImgUrl);

    
    var imgurl;
    var imgs = [];  //商品head展示图片
    var imgArr = imgUploadShow('content-img-select','content-img-show');
    //新图删除
    $('#content-img-show').on('click','.cancle',function(){
        var index = $(this).parent().index();
        imgArr.splice(index,1);
        var contentImgList = document.getElementById('content-img-show');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('new')[0];
        var contentImgItem = document.getElementsByClassName('content-img-item');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])

    })
    //旧图删除
    $('#content-img-show').on('click','.del',function(){
        var index = $(this).parent().index();
        // console.log(index);
        imgs.splice(index,1);
        // console.log(imgs)
        var contentImgList = document.getElementById('content-img-show');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('old')[0];
        var contentImgItem = document.getElementsByClassName('content-old-img-item');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])
        // // console.log(imgs);
    })
    $('#upload-content-img').on('click',function(){
        allImgUpload(imgArr,setContentImgUrl)
    });
    function setContentImgUrl(res){
        console.log(res)
        if(res.length != 0){
            imgurl = {
                banner_img : res
            } ;
            imgs.push(imgurl)
            // console.log(imgs);
            $('#upload-content-img').css('display','none');
        }
    }


    var imgurl2;
    var imgs2 = [];  //商品head展示图片
    var imgArr2 = imgUploadShow('content-img-select2','content-img-show2');
    //新图删除
    $('#content-img-show2').on('click','.cancle',function(){
        var index = $(this).parent().index();
        imgArr.splice(index,1);
        var contentImgList = document.getElementById('content-img-show2');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('new')[0];
        var contentImgItem = contentNewImgList.getElementsByClassName('content-img-item');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])

    })
    //旧图删除
    $('#content-img-show2').on('click','.del',function(){
        var index = $(this).parent().index();
        // // console.log(index);
        imgs2.splice(index,1);
        var contentImgList = document.getElementById('content-img-show2');
        // // console.log(contentImgList);
        var contentNewImgList = contentImgList.getElementsByClassName('old')[0];
        var contentImgItem = contentNewImgList.getElementsByClassName('content-old-img-item2');
        // // console.log(contentImgItem);
        contentNewImgList.removeChild(contentImgItem[index])
        // // console.log(imgs);
    })
    $('#upload-content-img2').on('click',function(){
        allImgUpload(imgArr2,setContentImgUrl2)
    });
    function setContentImgUrl2(res){
        // console.log(res)
        if(res.length != 0){
            imgurl2 = {
                url:res
            } ;
            imgs2.push(imgurl2)
            // console.log(imgs2);
            $('#upload-content-img2').css('display','none');
        }
    }
    
    $('#GoodsModal').on('show.bs.modal',function(event){
        var modal = $(this);
        var btnThis = $(event.relatedTarget);
        var type = btnThis.data('type');
        modal.find('#upType').val(type);
        // modal.find('#upload-content-img').css('display','block');
        modal.find('#goodsId').val('');
        // // console.log(type);
        var goodsName = modal.find('#goodsName');
        goodsName.val('');
        var shopPrice = modal.find('#shopPrice');
        shopPrice.val('');
        var shopNumber = modal.find('#shopNumber');
        shopNumber.val('')
        var goodsDesc = modal.find('#goodsDesc');
        goodsDesc.val('');
        var shopSpecifications = modal.find('#shopSpecifications')
        shopSpecifications.val('')
        var shopImg = modal.find('#goods-img-url');
        shopImg.val('');

        modal.find('#content-img-show .old').html('');
        modal.find('#content-img-show .new').html('');//可能存在bug
        modal.find('#content-img-show2 .old').html('');
        modal.find('#content-img-show2 .new').html('');//可能存在bug
        modal.find("#goods-img-show").html(`<div>图片预览</div>`);
        $('#upload-content-img').css('display','none');
        $('#upload-content-img2').css('display','none');
        //分类
        var obj = $(".class-checked");
        obj.attr('checked',false);

        var parameterItemAre = modal.find('.parameterItemAre')
        parameterItemAre.html('')

        //根据type判断是2修改还是1新增
        if(type == 1){
            modal.find('#GoodsModalLabel').text('添加商品');
        }else if(type == 2){
            modal.find('#GoodsModalLabel').text('修改商品信息');
            var goodsId = btnThis.data('id')
            modal.find('#goodsId').val(goodsId);
            var goodsInfo = '';
            for(var i in goodsList){
                if(goodsList[i].id == goodsId){
                    goodsInfo = goodsList[i]
                    break;
                }
            }
            console.log(goodsInfo)
            goodsName.val(goodsInfo.product_name);
            shopPrice.val(goodsInfo.jf);
            shopSpecifications.val(goodsInfo.gg);
            shopImg.val(goodsInfo.head_img);
            shopNumber.val(goodsInfo.no_pay)
            modal.find('#goods-img-show').html(`<img src="${goodsInfo.head_img}" />`);

            imgs = goodsInfo.top_img;
            var top_img = goodsInfo.top_img;
            // // console.log(head_banner);
            var html = '';
            for(var j in top_img){
                html+= `
                    <div class="content-old-img-item">
                        <img src="${top_img[j].banner_img}" alt="">
                        <div class="del themeColor">删 除</div>
                    </div>
                `
            }
            modal.find('#content-img-show .old').html(html);

            imgs2 = goodsInfo.content_img;
            var content_img = goodsInfo.content_img;
            // // console.log(head_banner);
            var html2 = '';
            for(var z in content_img){
                html2 += `
                    <div class="content-old-img-item">
                        <img src="${content_img[z].url}" alt="">
                        <div class="del themeColor">删 除</div>
                    </div>
                `
            }
            modal.find('#content-img-show2 .old').html(html2);

            obj.each(function(){
                var that = $(this);
                if(that.val() == goodsInfo.class_id){
                    // console.log(that.val());
                    that.prop('checked',true);
                }
            })


            var html3 = ''
            
            for(var p in goodsInfo.canshu){
                
                html3 += `
                            <div class="parameterItem">
                                <div class="parameter-group">
                                    <label for="parameter-name">名称</label>
                                    <input type="text" name="name" class="parameter-name" value="${goodsInfo.canshu[p].name}">
                                </div>
                                <div class="parameter-group">
                                    <label for="parameter-value">内容</label>
                                    <input type="text" name="value" class="parameter-value" value="${goodsInfo.canshu[p].text}">
                                </div>
                            </div>
                `
                index ++
            }
            $('.parameterItemAre').append(html3)

        }

    })
    
    //添加参数
    var index = 0
    $('#parameterBtn').on('click',function(){
        index ++ 
        var html = `
                    <div class="parameterItem">
                        <div class="parameter-group">
                            <label for="parameter-name">名称</label>
                            <input type="text" name="name" class="parameter-name">
                        </div>
                        <div class="parameter-group">
                            <label for="parameter-value">内容</label>
                            <input type="text" name="value" class="parameter-value">
                        </div>
                    </div>
        `
        
        $('.parameterItemAre').append(html)
        if(index > 0){
            $('#parameterDelBtn').css('display','block')
        }
    })

    //删除
    $('#parameterDelBtn').on('click',function(){
        index --
        $('.parameterItemAre').children('.parameterItem').eq(index).remove()
        if(index == 0){
            $('#parameterDelBtn').css('display','none')
        }
    })

    /** 添加 修改 **/
    $('#addGoods').on('click',function(){
        var shopType = $("#upType").val();
        // console.log('type:',type);
        if(index == 0){
            alert('请填写参数')
        }
        var nameList = []
        var parameterNameList = $('.parameterItemAre .parameter-name')
        parameterNameList.each(function(){
            var that = $(this);
            nameList.push(that.val())
        })
        var valueList = []
        var parameterValueList = $('.parameterItemAre .parameter-value')
        parameterValueList.each(function(){
            var that = $(this);
            valueList.push(that.val())
        })
        var parameterList = []
        for(var i=0;i < index;i++){
            var data = {
                name: nameList[i],
                text: valueList[i]
            }
            parameterList.push(data)
            
        }
        //获取选择的类别
        var obj = document.getElementsByClassName("class-checked");
        var check_class = '';
        for(k in obj){
            if(obj[k].checked)
                check_class=obj[k].value;
        }
        if(check_class)
        // // console.log(check_class)
        
        //获取商品名称
        var goodsName = $('#goodsName').val();
        //获取商品价格
        var shopPrice = $('#shopPrice').val(); 
        var shopNumber = $('#shopNumber').val()
        //获取商品规格
        var shopSpecifications = $('#shopSpecifications').val();
        //获取简介
        var goodsDesc = $('#goodsDesc').val();
        //获取缩略图
        var shopImg = $('#goods-img-url').val();
        
        
        //数据
        if(goodsName == ''||shopPrice == ''||goodsDesc == '' || shopImg=='' || check_class == '' ||shopNumber == '' || shopSpecifications == ''){
            alert('请将信息填写完整！')
        }else{
            if(imgs.length == 0){
                alert('请上传商品展示图片！')
                return
            }
            if(imgs2.length == 0){
                alert('请上传商品详情图片！')
                return
            }
            var data = {}
            if(shopType == 1){
                data = {
                    "product_name": goodsName,
                    "jf":shopPrice,
                    "no_pay": shopNumber,
                    "head_img":shopImg,
                    "content_img": imgs2,
                    "top_img": imgs,
                    "class_id": check_class,
                    "gg": shopSpecifications,
                    "canshu": parameterList,
                    "community_id": global.community_id    
                }
            }else if(shopType ==2){
                //修改
                var id = $("#goodsId").val();
                data = {
                    "id": id,
                    "product_name": goodsName,
                    "jf":shopPrice,
                    "no_pay": shopNumber,
                    "head_img":shopImg,
                    "content_img": imgs2,
                    "top_img": imgs,
                    "class_id": check_class,
                    "gg": shopSpecifications,
                    "canshu": parameterList,
                    "community_id": global.community_id    
                }
            }
            
            data = JSON.stringify(data);
            console.log(data)
            var text = ''
            if(shopType == 2){
                text = '商品信息，修改成功！';
            }else if(shopType == 1){
                text = '新的商品，添加成功！';
            }
            console.log(shopType)
            postAjax(`${global.apiUrl}/operation_community_jf_shop_product`,function(res){
                console.log(res)
                if(res == 1){
                    alert(text);
                    $('#GoodsModal').modal('hide');
                    getGoodsList(goodsPageNo,showNum,type,like);         
                }
            },{
                type:shopType,
                pro: data
            })
        }
    })
    /** 删除 **/
    $('#goodsList').on('click','.delete',function(){
        var goodsId = $(this).data('id');
        var f = confirm('是否删除该商品');
        if(f){
            getAjax(`${global.apiUrl}/operation_community_jf_shop_product`,function(res){
                console.log(res);
                if(res == 1){
                    alert('商品删除成功！');
                    getGoodsList(goodsPageNo,showNum,type,like);
                }
            },{
                type:3,
                id:goodsId
            })
        }

    })

    /***
     * 积分商城部分 end
     ***/


    
});
    